package com.sourcemuch.im.caiba.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import androidx.annotation.Nullable;

import com.sourcemuch.im.caiba.CaiBaChatApp;
import com.sourcemuch.im.caiba.R;import com.sourcemuch.im.caiba.R2;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.HashMap;

import cn.wildfire.chat.app.Config;
import cn.wildfire.chat.app.extendsion.classes.WXLoginRequest;
import cn.wildfire.chat.app.extendsion.classes.WeiXinUserInfoRequest;
import cn.wildfire.chat.app.extendsion.https.OkHttpRequest;
import cn.wildfire.chat.app.extendsion.https.ReqCallBack;
import cn.wildfire.chat.app.extendsion.https.ServerUrlClient;
import cn.wildfire.chat.app.extendsion.ui.CustomAppUIDialog;
import cn.wildfire.chat.app.extendsion.ui.TipDialog;
import cn.wildfire.chat.app.extendsion.ui.ToastTip;
import cn.wildfire.chat.app.extendsion.utils.TextUtils;
import cn.wildfire.chat.app.login.SMSLoginActivity;

/**
 * Create by HEKE, 2019/10/14 9:57
 * TODO 微信回调操作界面
 */
public class WXEntryActivity extends Activity implements IWXAPIEventHandler, WeiXinUserInfoRequest.OnSourceMuchWXAuthListener {

    /**
     * 微信账号绑定手机申请
     */
    public static final int REQUEST_BIND_MOBILE = 10001;

    protected IWXAPI iwxapi;

    // 来自请求类型标签
    protected String state;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try {
            iwxapi = WXAPIFactory.createWXAPI(this, Config.WXAppID, true);
            iwxapi.registerApp(Config.WXAppID);
            iwxapi.handleIntent(getIntent(), this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onReq(BaseReq baseReq) {
    }

    @Override
    public void onResp(BaseResp baseResp) {
        try {
            if (baseResp.errCode == 0) {
                SendAuth.Resp resp = (SendAuth.Resp) baseResp;
                state = resp.state;
                new WeiXinUserInfoRequest(this, resp.code, this);
            } else {
                ToastTip.tip(getString(R.string.weixin_athu_failed));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (iwxapi != null) {
            iwxapi.handleIntent(intent, this);
        }
    }

    @Override
    public void result(WXToken wxToken, WXUserInfo wxUserInfo, int req_error) {
        try {
            // 账号与安全中心绑定微信
            if (state.equals("sourcemuch_wechat_sdk_bindweixin")) {
                ((CaiBaChatApp) getApplicationContext()).wxUserInfo = wxUserInfo;
                finish();
            } else {
                // 检测后台是否已经包含此微信账户
                HashMap<String, Object> params = new HashMap<>();
                params.put("openId", wxUserInfo.openid);
                params.put("unionId", wxUserInfo.unionid);
                OkHttpRequest.getNewInstance(this).requestAsynJsonObject(ServerUrlClient.WX_EXISTED_CHECK, params, new ReqCallBack<String>() {
                    @Override
                    public void onReqSuccess(String result) {
                        try {
                            if (!TextUtils.isTextEmpty(result)) {
                                // 微信账户已注册
                                if (result.contains("result")) {
                                    wxLogin(wxUserInfo);
                                }
                                // 此微信账户不存在
                                else {
                                    TipDialog.showCustomDialog(WXEntryActivity.this, getString(R.string.wendy_title), getString(R.string.bind_mobile_msg), new String[]{getString(R.string.confirm), getString(R.string.cancle_but)}
                                            , CustomAppUIDialog.TYPE_CONFIRM_CANCLE, false, 2, true, new TipDialog.OnMsgTipDialogListener() {
                                                @Override
                                                public void then(boolean confirm,boolean outtouch) {
                                                    if (confirm) {
                                                        // 跳转进行绑定手机界面
                                                        Intent toBindMobile = new Intent(WXEntryActivity.this, SMSLoginActivity.class);
                                                        toBindMobile.putExtra("wxUserInfo", wxUserInfo);
                                                        startActivityForResult(toBindMobile, REQUEST_BIND_MOBILE);
                                                    } else {
                                                        // 以微信创建新账号
                                                        wxLogin(wxUserInfo);
                                                    }
                                                }
                                            });
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onReqFailed(String errorMsg) {
                        Log.e("#### onReqFailed ", " errorMsg : " + errorMsg);
                    }
                }).request();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // 返回绑定数据内容或者取消绑定内容，直接调用登入
        if (requestCode == REQUEST_BIND_MOBILE) {
            wxLogin(data.getParcelableExtra("wxUserInfo"));
            // 取消授权，结束此页面
            if (resultCode == Activity.RESULT_CANCELED) {
                finish();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 微信登入
     *
     * @param wxUserInfo
     */
    protected void wxLogin(WXUserInfo wxUserInfo) {
        try {
            new WXLoginRequest(this, wxUserInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
